package config.graceful;

import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.PollingServerListUpdater;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

@Slf4j
public class SelfServerListUpdater extends PollingServerListUpdater {

    private final ServerListListener listener;

    public SelfServerListUpdater(ServerListListener listener) {
        this.listener = listener;
    }

    @Override
    public void start(UpdateAction updateAction) {
        String clientName = getClientName(updateAction);
        listener.listen(clientName, () -> {
            log.info("refresh server info. {}", clientName);
            updateAction.doUpdate();
        });
    }

    private String getClientName(UpdateAction updateAction) {
        try {
            Class<?> bc = updateAction.getClass();
            Field field = bc.getDeclaredField("this$0");
            field.setAccessible(true);
            BaseLoadBalancer baseLoadBalancer = (BaseLoadBalancer) field.get(updateAction);
            return baseLoadBalancer.getClientConfig().getClientName();
        } catch (Exception e) {
            log.info("getClientName exception ：{}", e);
            throw new IllegalStateException(e);
        }
    }
}
